package com.nbufe.handler;

import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import com.nbufe.common.core.utils.StringUtils;
import com.nbufe.utils.HttpContextUtils;
import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.LongValue;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;

/**
 * @author LZH
 * @date 2023/3/25
 */
@Slf4j
public class MyTenantLineHandlerImpl implements TenantLineHandler {

    /**
     * 租户ID请求头名称
     */
    public static final String TENANT_ID_HEADER = "tenant-id";

    /**
     * 默认租户ID
     */
    public static final Long DEFAULT_TENANT_ID = 1L;

    /**
     * 不进行租户处理的table
     */
    private static final List<String> IGNORE_TABLES = Arrays.asList("material");

    @Override
    public Expression getTenantId() {
        HttpServletRequest request = null;
        try {
            request = HttpContextUtils.getRequest();
        } catch (Exception e) {
            log.error("HttpContextUtils.getRequest() error");
        }
        String id = "";
        if (request != null) {
            id = request.getHeader("tenant-id");
        }
        if (StringUtils.isEmpty(id)) {
            id = "-1";
        }
        log.debug(id + "----------");
        Long tenantId = Long.valueOf(id);
//        Long tenantId = Optional.ofNullable(HttpContextUtils.getRequestHeader(TENANT_ID_HEADER))
//                .map(Long::valueOf)
//                //.orElseThrow(() -> new RuntimeException("解析请求头中的X—TENANT-ID失败！"));
//                .orElseGet(() -> {
//                    log.info("解析请求头中的X-TENANT-ID失败 - 使用默认租户ID: {}", DEFAULT_TENANT_ID);
//                    return DEFAULT_TENANT_ID;
//                });
        return new LongValue(tenantId);
    }

    @Override
    public String getTenantIdColumn() {
        //默认tenant_id
        return "tenant_id";
    }

    @Override
    public boolean ignoreTable(String tableName) {
        //是否忽略此table的租户处理逻辑
        return IGNORE_TABLES.contains(tableName);
    }
}
